<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { api, toAbsoluteUrl } from '@/utils/request'
import { useAuthStore } from '@/stores/auth'

const router = useRouter()
const auth = useAuthStore()
const rooms = ref<any[]>([])
const loading = ref(false)

// 密码验证相关
const showPasswordDialog = ref(false)
const passwordInput = ref('')
const currentRoom = ref<any>(null)
const verifying = ref(false)

async function fetchRooms() {
  loading.value = true
  try {
    const resp = await api.get('/api/chat/rooms')
    const data = await resp.json()
    rooms.value = data.rooms || []
  } finally {
    loading.value = false
  }
}

async function enterRoom(room: any) {
  // 检查是否已登录，未登录则跳转到登录页面
  if (!auth.user) {
    router.push('/login')
    return
  }

  try {
    // 检查是否需要密码
    const resp = await api.get(`/api/chat/rooms/${room.id}/check-password`)
    const data = await resp.json()

    if (data.needPassword) {
      // 需要密码，显示密码输入框
      currentRoom.value = room
      passwordInput.value = ''
      showPasswordDialog.value = true
    } else {
      // 不需要密码，直接进入
      router.push(`/chat/${room.id}`)
    }
  } catch (error) {
    console.error('채팅방 비밀번호 확인 실패:', error)
    // 如果检查失败，尝试直接进入
    router.push(`/chat/${room.id}`)
  }
}

async function verifyPassword() {
  if (!currentRoom.value || !passwordInput.value.trim()) {
    alert('비밀번호를 입력해주세요')
    return
  }

  verifying.value = true
  try {
    const resp = await api.post(`/api/chat/rooms/${currentRoom.value.id}/verify-password`, {
      password: passwordInput.value.trim()
    })

    if (resp.ok) {
      const data = await resp.json()
      if (data.success) {
        showPasswordDialog.value = false
        router.push(`/chat/${currentRoom.value.id}`)
      }
    } else {
      // 处理HTTP错误响应
      let errorMsg = '비밀번호 확인에 실패했습니다'
      try {
        const errorData = await resp.json()
        errorMsg = errorData.error || errorMsg
      } catch {
        // 忽略解析错误，使用默认消息
      }
      alert(errorMsg)
    }
  } catch {
    // 处理网络错误等
    alert('비밀번호 확인에 실패했습니다')
  } finally {
    verifying.value = false
  }
}

function cancelPasswordDialog() {
  showPasswordDialog.value = false
  currentRoom.value = null
  passwordInput.value = ''
}

onMounted(fetchRooms)
</script>

<template>
  <div class="chat-list">
    <div class="grid">
      <div v-for="r in rooms" :key="r.id" class="chat-card" @click="enterRoom(r)">
        <div class="thumb">
          <img :src="toAbsoluteUrl(r.coverUrl) || `https://picsum.photos/seed/chat-${r.id}/320/180`" alt="cover" />
        </div>
        <div class="content">
          <div class="title">{{ r.displayName || r.title || '채팅방' }}</div>
          <div class="meta">
            <span class="desc">{{ r.description || '온라인' }}</span>
          </div>
        </div>
        <div class="side">입장</div>
      </div>
    </div>

    <!-- 비밀번호 입력 대화상자 -->
    <div v-if="showPasswordDialog" class="password-overlay" @click="cancelPasswordDialog">
      <div class="password-dialog" @click.stop>
        <div class="dialog-header">
          <h3>채팅방 비밀번호 필요</h3>
          <button class="close-btn" @click="cancelPasswordDialog">×</button>
        </div>
        <div class="dialog-body">
          <p>{{ currentRoom?.displayName || currentRoom?.title || '채팅방' }}에 입장하려면 비밀번호가 필요합니다</p>
          <input
            v-model="passwordInput"
            type="password"
            placeholder="비밀번호를 입력하세요"
            class="password-input"
            @keyup.enter="verifyPassword"
            autofocus
          />
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="cancelPasswordDialog">취소</button>
          <button class="confirm-btn" @click="verifyPassword" :disabled="verifying">
            {{ verifying ? '확인 중...' : '입장' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.chat-list {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
  padding: var(--space-4);
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
  gap: var(--space-4);
}

.chat-card {
  display: flex;
  align-items: stretch;
  background: white;
  border: 1px solid var(--color-border);
  border-radius: var(--radius-lg);
  overflow: hidden;
  cursor: pointer;
  transition: all 0.2s ease;
  box-shadow: var(--shadow-sm);
}

.chat-card:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-lg);
  border-color: var(--color-primary);
}

.thumb {
  width: 120px;
  height: 80px;
  background: var(--color-surface);
  flex-shrink: 0;
  position: relative;
  overflow: hidden;
}

.thumb img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  display: block;
  transition: transform 0.2s ease;
}

.chat-card:hover .thumb img {
  transform: scale(1.05);
}

.content {
  padding: var(--space-3) var(--space-4);
  color: var(--color-text);
  display: flex;
  flex-direction: column;
  justify-content: center;
  flex: 1;
  min-width: 0;
}

.title {
  font-weight: 600;
  font-size: 0.95rem;
  line-height: 1.3;
  margin-bottom: var(--space-1);
  color: var(--color-text);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.meta {
  color: var(--color-text-muted);
  display: flex;
  align-items: center;
  gap: var(--space-2);
  font-size: 0.8rem;
}

.meta .desc {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  flex: 1;
}

.side {
  background: var(--color-primary);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 0.8rem;
  padding: 0 var(--space-3);
  min-width: 60px;
  position: relative;
  overflow: hidden;
}

.side::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, var(--color-primary), var(--color-primary-dark));
  opacity: 0;
  transition: opacity 0.2s ease;
}

.chat-card:hover .side::before {
  opacity: 1;
}

.side span {
  position: relative;
  z-index: 1;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: var(--space-8);
  color: var(--color-text-muted);
}

.empty-state .icon {
  font-size: 3rem;
  margin-bottom: var(--space-4);
  opacity: 0.5;
}

.empty-state .message {
  font-size: 1.1rem;
  margin-bottom: var(--space-2);
}

.empty-state .description {
  font-size: 0.9rem;
  opacity: 0.8;
}

/* 加载状态 */
.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--space-8);
  color: var(--color-text-muted);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .grid {
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
    gap: var(--space-3);
  }

  .chat-list {
    padding: var(--space-3);
  }
}

@media (max-width: 768px) {
  .grid {
    grid-template-columns: 1fr;
    gap: var(--space-3);
  }

  .chat-card {
    flex-direction: column;
    max-width: none;
  }

  .thumb {
    width: 100%;
    height: 120px;
  }

  .content {
    padding: var(--space-3);
  }

  .side {
    padding: var(--space-2);
    min-width: auto;
    justify-content: center;
  }

  .chat-list {
    padding: var(--space-2);
  }
}

@media (max-width: 480px) {
  .chat-card {
    border-radius: var(--radius-md);
  }

  .thumb {
    height: 100px;
  }

  .title {
    font-size: 0.9rem;
  }

  .meta {
    font-size: 0.75rem;
  }
}

/* 密码对话框样式 */
.password-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.password-dialog {
  background: var(--color-bg);
  border-radius: 12px;
  width: 90%;
  max-width: 400px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  overflow: hidden;
}

.dialog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  border-bottom: 1px solid var(--color-border);
}

.dialog-header h3 {
  margin: 0;
  font-size: 1.1rem;
  color: var(--color-text);
}

.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  color: var(--color-text-secondary);
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: var(--color-text);
}

.dialog-body {
  padding: 20px;
}

.dialog-body p {
  margin: 0 0 16px 0;
  color: var(--color-text-secondary);
  font-size: 0.9rem;
}

.password-input {
  width: 100%;
  padding: 12px;
  border: 1px solid var(--color-border);
  border-radius: 8px;
  font-size: 1rem;
  background: var(--color-bg-secondary);
  color: var(--color-text);
  box-sizing: border-box;
}

.password-input:focus {
  outline: none;
  border-color: var(--color-primary);
}

.dialog-footer {
  display: flex;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid var(--color-border);
}

.cancel-btn, .confirm-btn {
  flex: 1;
  padding: 12px;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  cursor: pointer;
  transition: all 0.2s;
}

.cancel-btn {
  background: var(--color-bg-secondary);
  color: var(--color-text-secondary);
}

.cancel-btn:hover {
  background: var(--color-border);
}

.confirm-btn {
  background: var(--color-primary);
  color: white;
}

.confirm-btn:hover:not(:disabled) {
  background: var(--color-primary-dark);
}

.confirm-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>
